﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using d1Common.WebController;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using d1Common;
using d1Project.Modules.Common.do4A.Models;
using Newtonsoft.Json;
using d1Project.Tools.PagedList;
using d1Project.Tools;
using Newtonsoft.Json.Linq;
using d1Project.Modules.Common.do4A.Domain;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/User1")]
    public class User1Controller : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        //[PermissionCheck(Id = "do4A$User1", Operation = 0)]
        public async Task<IHttpActionResult> Get([FromUri]User1GetVm model)
        {
            var entity = db.User1s.AsQueryable();
            if (!string.IsNullOrEmpty(model.Code))
            {
                entity = entity.Where(p => p.Code.Contains(model.Code));
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                entity = entity.Where(p => p.Name.Contains(model.Name));
            }
            if (!string.IsNullOrEmpty(model.Email))
            {
                entity = entity.Where(p => p.Email == model.Email);
            }
            if (!string.IsNullOrEmpty(model.MobilePhone))
            {
                entity = entity.Where(p => p.MobilePhone == model.MobilePhone);
            }
            if (!string.IsNullOrEmpty(model.DeptId))
            {
                entity = entity.Where(x => x.DeptId == model.DeptId);
            }

            var result = await entity.OrderBy(p => p.CreateTime).ToPagedListAsync(model);
            return Ok(new { total = entity.Count(), rows = result });
        }

        //[PermissionCheck(Id = "do4A$User1", Operation = 0)]
        public async Task<IHttpActionResult> Get(string Id)
        {
            if (string.IsNullOrEmpty(Id)) this.Error("用户Id不能为空");
            var entity = await db.User1s.FindAsync(Id);
            if (entity == null) this.Error("找不到用户");
            return Ok(entity);
        }

        //[PermissionCheck(Id = "do4A$User1", Operation = 1)]
        public async Task<IHttpActionResult> Post(User1PostVm model)
        {
            //if (!string.IsNullOrEmpty(model.Code))
            //{
            //    var oldCode = await db.User1s.Where(p => p.Code == model.Code).FirstOrDefaultAsync();
            //    if (oldCode != null) this.Error("编码已存在");
            //}
            if (!string.IsNullOrEmpty(model.MobilePhone))
            {
                var oldMobilePhone = await db.User1s.Where(p => p.MobilePhone == model.MobilePhone).FirstOrDefaultAsync();
                if (oldMobilePhone != null) this.Error("手机号已存在");
            }
            User1 entity = new User1();
            entity.Id = doServices.Instance.DoCore.getGUID();
            //entity.Code = model.Code;
            entity.Name = model.Name;
            entity.PinYin = AuthenticationMgr.Instance.GetUserNamePinYin(model.Name).ToLower();
            entity.Icon = model.Icon;
            entity.Sex = model.Sex;
            entity.Birthday = model.Birthday;
            entity.Email = model.Email;
            entity.MobilePhone = model.MobilePhone;
            entity.IdCard = model.IdCard;
            entity.IsAvailable = model.IsAvailable;
            entity.DeptId = model.DeptId;
            entity.AreaId = model.AreaId;
            entity.RoleId = model.RoleId;
            entity.CreateById = this.UserId;
            entity.CreateByName = this.UserName;
            entity.CreateTime = DateTime.Now;
            entity.UpdateById = this.UserId;
            entity.UpdateByName = this.UserName;
            entity.UpdateTime = DateTime.Now;
            db.User1s.Add(entity);
            await dbContext.SaveChangesAsync();
            return Ok();
        }

        //[PermissionCheck(Id = "do4A$User1", Operation = 2)]
        public async Task<IHttpActionResult> Put(User1PutVm model)
        {
            if (!ModelState.IsValid) this.Error("请求参数不正确");

            var entity = db.User1s.Find(model.Id);
            //if (entity.Code != model.Code)
            //{
            //    var oldCode = await db.User1s.Where(p => p.Code == model.Code).FirstOrDefaultAsync();
            //    if (oldCode != null) this.Error("编码已存在");
            //}
            if (entity.MobilePhone != model.MobilePhone)
            {
                var oldMobilePhone = await db.User1s.Where(p => p.MobilePhone == model.MobilePhone).FirstOrDefaultAsync();
                if (oldMobilePhone != null) this.Error("手机号已存在");
            }
            //entity.Code = model.Code;
            entity.Id = model.Id;
            entity.Name = model.Name;
            entity.PinYin = AuthenticationMgr.Instance.GetUserNamePinYin(model.Name).ToLower();
            entity.Icon = model.Icon;
            entity.Sex = model.Sex;
            entity.Birthday = model.Birthday;
            entity.Email = model.Email;
            entity.MobilePhone = model.MobilePhone;
            entity.IdCard = model.IdCard;
            entity.IsAvailable = model.IsAvailable;
            entity.DeptId = model.DeptId;
            entity.AreaId = model.AreaId;
            entity.RoleId = model.RoleId;
            entity.UpdateById = this.UserId;
            entity.UpdateByName = this.UserName;
            entity.UpdateTime = DateTime.Now;
            await db.SaveChangesAsync();
            return Ok();
        }

        //[PermissionCheck(Id = "do4A$User1", Operation = 4)]
        public async Task<IHttpActionResult> Delete(string id)
        {
            if (string.IsNullOrEmpty(id)) this.Error("id不能为空");
            var entity = await db.User1s.FindAsync(id);
            db.User1s.Remove(entity);

            var user1Pwds = db.User1Pwds.Find(id);
            if (user1Pwds != null) db.User1Pwds.Remove(user1Pwds);
            await db.SaveChangesAsync();
            return Ok();
        }
        public async Task<IHttpActionResult> Post(string id)
        {
            if (string.IsNullOrEmpty(id)) this.Error("id不能为空");
            var entity = await db.User1s.FindAsync(id);
            db.User1s.Remove(entity);

            var user1Pwds = db.User1Pwds.Find(id);
            if (user1Pwds != null) db.User1Pwds.Remove(user1Pwds);
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class User1GetVm : VmBase
    {
        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        public string MobilePhone { get; set; }

        /// <summary>
        /// 是否有效 (1：有效，其它无效)
        /// </summary>
        public string IsAvailable { get; set; }

        public string DeptId { get; set; }
    }

    public class User1PostVm
    {
        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 性别：0：女 1：男
        /// </summary>
        public string Sex { get; set; }

        /// <summary>
        /// 出生日期：yyyy-MM-dd
        /// </summary>
        public string Birthday { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        public string MobilePhone { get; set; }

        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; }

        /// <summary>
        /// 是否有效 (1：有效，其它无效)
        /// </summary>
        [Required]
        public string IsAvailable { get; set; }

        /// <summary>
        /// 部门Id
        /// </summary>
        public string DeptId { get; set; }
        /// <summary>
        /// 区域Id
        /// </summary>
        public string AreaId { get; set; }

        /// <summary>
        /// 角色Id
        /// </summary>
        public string RoleId { get; set; }
    }

    public class User1PutVm
    {
        [Required]
        public string Id { get; set; }

        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 性别：0：女 1：男
        /// </summary>
        public string Sex { get; set; }

        /// <summary>
        /// 出生日期：yyyy-MM-dd
        /// </summary>
        public string Birthday { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        public string MobilePhone { get; set; }

        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; }

        /// <summary>
        /// 是否有效 (1：有效，其它无效)
        /// </summary>
        [Required]
        public string IsAvailable { get; set; }

        /// <summary>
        /// 部门Id
        /// </summary>
        public string DeptId { get; set; }

        /// <summary>
        /// 区域Id
        /// </summary>
        public string AreaId { get; set; }

        /// <summary>
        /// 角色Id
        /// </summary>
        public string RoleId { get; set; }
    }
}